<template>
  <div>
    <h1>菜品管理</h1>
     <el-button type="success" @click="dishtadd()" >新增菜品</el-button>
    <el-input v-model="page.DishesName" placeholder="请输入菜品名称" style="width: 200px;"/>
    <el-button type="primary" @click="getlist()">查询</el-button><br><br>
  </div>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column fixed prop="dishesName" label="菜品名称" width="150" />
    <el-table-column prop="sumSales" label="总销量" width="120" />
    <el-table-column prop="inventory" label="剩余库存" width="150"  />
    <el-table-column prop="dishesTaste" label="点餐中开启" width="150">
      <template #default="scoped">
         <span>{{ scoped.row.dishesTaste == 1 ? "开启" : "关闭"}}</span>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作列" min-width="120" >
      <template #default="{row}">
        <el-button link type="primary" size="small" @click="handleClick(row.id)">
          删除
        </el-button>
        <el-button link type="primary" size="small" @click="showupdate(row)">修改</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 新增菜品弹框 -->
  <el-dialog v-model="dialogVisible" title="新增菜品" width="600px">
      <el-form :model="insertformDat" :rules="rules" ref="formRef">
        <!-- 菜品名称 -->
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="insertformDat.dishesName" placeholder="请输入" :maxlength="20"></el-input>
          <span class="input-tip">{{ insertformDat.dishesName.length }}/20</span>
        </el-form-item>
        <!-- 菜品图片 -->
        <!-- <el-form-item label="菜品图片">
          <el-upload
            v-model="insertformDat.dishesImg"
            :action="uploadUrl"
            :limit="6"
            :before-upload="beforeUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            multiple
            :auto-upload="false"
          >
            <el-button type="primary">上传图片</el-button>
            <img v-if="insertformDat.dishesImg" :src="insertformDat.dishesImg" class="avatar" style="width: 80px;height: 80px"/>
          </el-upload>
          <div class="upload-tip">
            上传图片可拖拽排序，支持6张，jpg jpeg.bmp.png格式，大小不超过2M，建议像素750*750（或比例1：1）
          </div>
        </el-form-item> -->
        <el-form-item label="菜品照片">
          <el-upload
    class="avatar-uploader"
    action="https://localhost:44392/PostImag"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="insertformDat.dishesImg" :src="insertformDat.dishesImg" class="avatar" style="width: 80px;height: 80px"/>
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
        </el-form-item>
        

        <!-- 菜品介绍 -->
        <el-form-item label="菜品介绍" prop="dishesDesc">
          <el-input type="textarea" v-model="insertformDat.dishesDesc" placeholder="请输入菜品简介" :maxlength="50"></el-input>
          <span class="input-tip">{{ insertformDat.dishesDesc.length }}/50</span>
        </el-form-item>
        <!-- 销售价 -->
        <el-form-item label="销售价">
          <!-- <el-radio-group v-model="insertformDat.salesPrice">
            <el-radio label="single">单一售价</el-radio>
            <el-radio label="规格">启用规格</el-radio>
          </el-radio-group>
          <el-form-item v-if="insertformDat.salesPrice ===0" prop="price" :rules="{ required: true, message: '请输入售价', trigger: 'blur', pattern: /^\d*(\.\d{0,1})?$/, messages: '仅可输入0-999999.9，保留小数点后一位' }">
            <el-input v-model="insertformDat.salesPrice" placeholder="请输入" style="width: 120px;"></el-input>
            <span class="price-unit">元</span>
          </el-form-item> -->
          <el-input v-model="insertformDat.salesPrice" placeholder="请输入销售价" ></el-input>
        </el-form-item>
        <el-form-item label="总销量">
          <el-input v-model="insertformDat.sumSales" placeholder="请输入总销量" ></el-input>
        </el-form-item>
        <!-- 库存 -->
        <el-form-item label="库存" prop="inventory" :rules="{ required: true, message: '请输入库存', trigger: 'blur', pattern: /^\d{0,6}$/, messages: '仅可输入0-999999整数值' }">
          <el-input v-model="insertformDat.inventory" placeholder="请输入" style="width: 120px;"></el-input>
          <span class="inventory-tip">库存为每日可售数量，下个营业日自动更新库存。</span>
        </el-form-item>
        <!-- 菜品口味 -->
        <el-form-item label="菜品口味">
      <el-radio-group v-model="insertformDat.dishesTaste">
        <el-radio :value="true">辣</el-radio>
        <el-radio :value="false">不辣</el-radio>
      </el-radio-group>
    </el-form-item>
        <!-- 菜品分组 -->
        <el-form-item label="菜品分组" prop="dishesGroupingName" >
          <el-select v-model="insertformDat.dishesGroupingId" placeholder="请选择分组">

            <el-option v-for="item in forms" :key="item.id" :value="item.id" :label="item.dishesGroupingName"></el-option>
          </el-select>
          <el-link type="primary" @click="openCreateGroupDialog=true">新建分组</el-link>
          
        </el-form-item>
        <!-- 售卖时段 -->
        <el-form-item label="销售时段">
      <el-col :span="11">
        <el-date-picker
          v-model="insertformDat.saleDate"
          type="date"
          placeholder="Pick a date"
          style="width: 100%"
        />
      </el-col>
      <el-col :span="2" class="text-center">
        <span class="text-gray-500">-</span>
      </el-col>
      <el-col :span="11">
        <el-time-picker
          v-model="insertformDat.saleDate"
          placeholder="Pick a time"
          style="width: 100%"
        />
      </el-col>
    </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </span>
      </template>
    </el-dialog>


 <!-- 修改菜品弹框 -->
 <el-dialog v-model="dialogVisibles" title="修改菜品" width="600px">
      <el-form :model="formData" :rules="rules" ref="formRef">
        <!-- 菜品名称 -->
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="formData.dishesName" placeholder="请输入" :maxlength="20"></el-input>
          <span class="input-tip">{{ formData.dishesName.length }}/20</span>
        </el-form-item>
        <!-- 菜品图片 -->
        <!-- <el-form-item label="菜品图片">
          <el-upload
            v-model="formData.dishesImg"
            :action="uploadUrl"
            :limit="6"
            :before-upload="beforeUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            multiple
            :auto-upload="false"
          >
            <el-button type="primary">上传图片</el-button>
            <img v-if="formData.dishesImg" :src="formData.dishesImg" class="avatar" style="width: 80px;height: 80px"/>
          </el-upload>
          <div class="upload-tip">
            上传图片可拖拽排序，支持6张，jpg jpeg.bmp.png格式，大小不超过2M，建议像素750*750（或比例1：1）
          </div>
        </el-form-item> -->
        <el-form-item label="菜品照片">
          <el-upload
    class="avatar-uploader"
    action="https://localhost:44392/PostImag"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="formData.dishesImg" :src="formData.dishesImg" class="avatar" style="width: 80px;height: 80px"/>
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
        </el-form-item>
        

        <!-- 菜品介绍 -->
        <el-form-item label="菜品介绍" prop="dishesDesc">
          <el-input type="textarea" v-model="formData.dishesDesc" placeholder="请输入菜品简介" :maxlength="50"></el-input>
          <span class="input-tip">{{ formData.dishesDesc.length }}/50</span>
        </el-form-item>
        <!-- 销售价 -->
        <el-form-item label="销售价">
          <!-- <el-radio-group v-model="formData.salesPrice">
            <el-radio label="single">单一售价</el-radio>
            <el-radio label="规格">启用规格</el-radio>
          </el-radio-group>
          <el-form-item v-if="formData.salesPrice ===0" prop="price" :rules="{ required: true, message: '请输入售价', trigger: 'blur', pattern: /^\d*(\.\d{0,1})?$/, messages: '仅可输入0-999999.9，保留小数点后一位' }">
            <el-input v-model="formData.salesPrice" placeholder="请输入" style="width: 120px;"></el-input>
            <span class="price-unit">元</span>
          </el-form-item> -->
          <el-input v-model="formData.salesPrice" placeholder="请输入销售价" ></el-input>
        </el-form-item>
        <el-form-item label="总销量">
          <el-input v-model="formData.sumSales" placeholder="请输入总销量" ></el-input>
        </el-form-item>
        <!-- 库存 -->
        <el-form-item label="库存" prop="inventory" :rules="{ required: true, message: '请输入库存', trigger: 'blur', pattern: /^\d{0,6}$/, messages: '仅可输入0-999999整数值' }">
          <el-input v-model="formData.inventory" placeholder="请输入" style="width: 120px;"></el-input>
          <span class="inventory-tip">库存为每日可售数量，下个营业日自动更新库存。</span>
        </el-form-item>
        <!-- 菜品口味 -->
        <el-form-item label="菜品口味">
      <el-radio-group v-model="formData.dishesTaste">
        <el-radio :value="true">辣</el-radio>
        <el-radio :value="false">不辣</el-radio>
      </el-radio-group>
    </el-form-item>
        <!-- 菜品分组 -->
        <el-form-item label="菜品分组" prop="dishesGroupingName" >
          <el-select v-model="formData.dishesGroupingId" placeholder="请选择分组">

            <el-option v-for="item in forms" :key="item.id" :value="item.id" :label="item.dishesGroupingName"></el-option>
          </el-select>
          <el-link type="primary" @click="openCreateGroupDialog=true">新建分组</el-link>
          
        </el-form-item>
        <!-- 售卖时段 -->
        <el-form-item label="销售时段">
      <el-col :span="11">
        <el-date-picker
          v-model="formData.saleDate"
          type="date"
          placeholder="Pick a date"
          style="width: 100%"
        />
      </el-col>
      <el-col :span="2" class="text-center">
        <span class="text-gray-500">-</span>
      </el-col>
      <el-col :span="11">
        <el-time-picker
          v-model="formData.saleDate"
          placeholder="Pick a time"
          style="width: 100%"
        />
      </el-col>
    </el-form-item>
      </el-form>
      <template #footer="scope">
        <span class="dialog-footer">
          <el-button @click="dialogVisibles = false">取消</el-button>
          <el-button type="primary" @click="submitForms()">修改</el-button>
        </span>
      </template>
    </el-dialog>





    <el-dialog v-model="openCreateGroupDialog" title="菜品分组" width="500">
    <el-form :model="forms">
      <el-form-item label="分组名称" :label-width="80">
        <el-input v-model="formData.dishesGroupingName" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="openCreateGroupDialog = false">取消</el-button>
        <el-button type="primary" @click="CreateGroupAdd">
          保存分组 
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script lang="ts" setup>
import { ref,onMounted,reactive } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import {useRouter} from 'vue-router'
import type { UploadProps } from 'element-plus'
const router = useRouter()

//弹框添加
const dialogVisible = ref(false)
const dialogVisibles=ref(false)
const openCreateGroupDialog = ref(false)
const formData = reactive({
  id: '',
  dishesName: '',
  dishesImg:'',
  dishesDesc: '',
  salesPrice:0,
  sumSales:0,
  inventory:0,
  dishesTaste:'',
  dishesGroupingId: '',
  saleDate: '',
  dishesGroupingName: ''
})


const insertformDat=reactive({
  dishesName: '',
  dishesImg:'',
  dishesDesc: '',
  salesPrice:0,
  sumSales:0,
  inventory:0,
  dishesTaste:'',
  dishesGroupingId: '',
  saleDate: '',
  dishesGroupingName: ''
})

const forms=ref<any>([])

// //上传图片路径
// const uploadUrl = ref('https://localhost:44392/PostImag'); 
// 表单验证规则
const rules = reactive({});
// 表单引用
const formRef = ref(null);

const dishtadd=()=>{
  dialogVisible.value= true
}


const submitForm=()=>{
  axios({
    url:"https://localhost:44392/PostDishes",
    method:"post",
    data:insertformDat
  }).then(res=>{
    console.log(res);
    if(res.data.code==200)
  {
    ElMessage({
      message: '添加成功',
      type: 'success',
    })
    dialogVisible.value = false
    getlist()
  }else{
    ElMessage({
      message: '添加失败',
      type: 'error',
    })
  }
  }).catch(err=>{
    console.log(err);
  })
}


const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response
  
) => {
  insertformDat.dishesImg = response
  formData.dishesImg = response
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile:any) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片类型必须是JPG类型!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能大于2MB!')
    return false
  }
  return true
}

// 新建分组
const CreateGroupAdd=()=>{
  axios({
    url:"https://localhost:44392/PostDishesGrouping",
    method:"post",
    data:formData
  }).then(res=>{
     if(res.data.code==200)
     {
      ElMessage({
        message: '添加成功',
        type: 'success',
      })
      openCreateGroupDialog.value = false
     }else
     {
      ElMessage.error("添加失败")
     }
  })
}

//弹窗修改
const showupdate=(row:any)=>{
  console.log(row);
  dialogVisibles.value= true
  formData.id=row.id
  formData.dishesName=row.dishesName
  formData.dishesImg=row.dishesImg
  formData.dishesDesc=row.dishesDesc
  formData.salesPrice=row.salesPrice
  formData.sumSales=row.sumSales
  formData.inventory=row.inventory
  formData.dishesTaste=row.dishesTaste
  formData.dishesGroupingId=row.dishesGroupingId
  formData.saleDate=row.saleDate
  formData.dishesGroupingName=row.dishesGroupingName
  console.log(formData.id);
}



const tableData = ref([])
const page=ref({
  DishesName:""
})

//生命周期函数
onMounted(() => {
  getlist();
  DishesGroupingBind()
})
 
// 获取列表
const getlist=()=>{
  axios({
    url:"https://localhost:44392/GetDishesGrouping",
    method:"get",
    params:page.value
  }).then(res=>{
    tableData.value=res.data.data;
    console.log(tableData.value);
  })
}

//删除
const handleClick = (id:any) => {
 
  axios.delete("https://localhost:44392/DeleteDishe?Id="+id).then(res=>{
    if(res.data.code==200)
  {
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    getlist();
  }else
  {
    ElMessage.error("删除失败")
  }
  })
}


//编辑
const submitForms=()=>{
  console.log(formData);

  dialogVisibles.value=true;
  axios.put("https://localhost:44392/PutDishes",formData).then(res=>{
    if(res.data.code==200)
  {
    ElMessage({
      message: '修改成功',
      type: 'success',
    })
    dialogVisibles.value=false;
    getlist();
  }else{
    ElMessage.error("修改失败")
  }
})
}


const DishesGroupingBind=()=>{
  
   axios({
    url:"https://localhost:44392/PostDishesGrouBing",
    method:"get",
    params:{}
   }).then(res=>{
    console.log(res.data);
    forms.value=res.data.data
   }).catch(err=>{
    console.log(err);
   })
}


</script>


<style scoped>
.dish-management {
  padding: 20px;
}
.page-title {
  margin-bottom: 10px;
  font-size: 20px;
  font-weight: bold;
}
.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.left-buttons {
  display: flex;
}
.right-filters {
  display: flex;
  align-items: center;
}
.status-filter {
  margin-right: 10px;
  display: flex;
  align-items: center;
}
.input-tip,
.price-unit,
.stock-tip,
.taste-tip,
.time-tip {
  display: block;
  font-size: 12px;
  color: #999;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>